package com.subframe7536.UserInfo.utils;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author subframe7536
 */
public class TimeUtil {

    /**
     * 获取时间戳
     *
     * @param isMillisecond 是否输出毫秒时间戳
     */
    public static Long getTimestamp(boolean isMillisecond) {
        long stamp;
        if (isMillisecond) {
            stamp = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        } else {
            stamp = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        }
        return stamp;
    }

    /**
     * 根据当前时间获取时间字符串
     *
     * @param pattern 时间格式
     */
    public static String getCurrentTimeString(String pattern) {
        String time;
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
            time = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter);
        } catch (Exception e) {
            time = "pattern error!";
        }
        return time;
    }

    /**
     * 根据指定时间获取时间字符串
     *
     * @param target 时间格式
     */
    public static String getTargetTimeString(LocalDateTime target) {
        return getTargetTimeString(target, "yyyy-MM-dd HH:mm:ss");
    }
    public static String getTargetTimeString(LocalDateTime target, String pattern) {
        String time;
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
            time = target.format(formatter);
        } catch (Exception e) {
            time = "pattern error!";
        }
        return time;
    }

    /**
     * <p>时间字符串转LocalDateTime</p>
     * 格式：yyyy-MM-dd HH:mm:ss
     */
    public static LocalDateTime getLocalDateTimeByTimeString(String timeString) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return LocalDateTime.parse(timeString, df);
    }

    /**
     * <p>时间字符串转LocalDateTime</p>
     * 格式自定义
     */
    public static LocalDateTime getLocalDateTimeByTimeString(String timeString, String pattern) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);
        return LocalDateTime.parse(timeString, df);
    }

}
